package com.xn.app.muying.sqlite;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;

public class DBManager {
    private SQLiteDatabase db;
    // 用户表
    public static final String USER_TABLE = DatabaseHelper.USER_TABLE;
    // 缓存表
    public static final String CACHE_TABLE = DatabaseHelper.CACHE_TABLE;
    // 体温监测设置表
    public static final String TEMPERATRUE_SET_TABLE = DatabaseHelper.TEMPERATRUE_SET_TABLE;
    // 体温监测数据表
    public static final String TEMPERATRUE_DATA_TABLE = DatabaseHelper.TEMPERATRUE_DATA_TABLE;

    public DBManager(Context context) {
        DatabaseHelper helper = new DatabaseHelper(context);
        // 因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0,
        // mFactory);
        // 所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里
        db = helper.getWritableDatabase();
    }

    /**
     * 用户登录添加用户数据
     *
     * @param access_token 用户token值
     * @param token_type   标识
     * @param userName     用户名
     */
    public void insertUser(String access_token, String token_type, String userName) {
        String sql = "insert into " + USER_TABLE
                + "(tel,access_token,token_type) values(?,?,?)";
        db.execSQL(
                sql,
                new Object[]{userName, access_token, token_type});
    }

    /**
     * 用户数据补充
     *
     * @param id                        用户主键
     * @param openId                    用户主键(预留)
     * @param identityId                身份证号
     * @param name                      姓名
     * @param pregnancyStatus           孕期状态参数
     * @param pregnancyStatusDisplay    孕期状态
     * @param preDeliveryDate           预产期
     * @param antenatalCareHospitalId   医院ID
     * @param antenatalCareHospitalName 医院名称
     * @param babyBirthday              宝宝生日
     * @param babyGender                宝宝性别
     * @param isVIP                     是否是VIP
     * @param isCanTrialVIP             是否可以试用会员
     * @param vipEndTime                会员截止日期
     * @param tel                       用户手机号
     */
    public void updateUser(String id, String openId, String identityId, String name, String pregnancyStatus,
                           String pregnancyStatusDisplay, String preDeliveryDate,
                           String antenatalCareHospitalId, String antenatalCareHospitalName,
                           String babyBirthday, String babyGender, int isVIP,
                           int isCanTrialVIP, String vipEndTime, String tel) {
        String sql = "update "
                + USER_TABLE
                + " set id= ? ,openId= ? , identityId= ? , name= ? , pregnancyStatus= ? , " +
                "pregnancyStatusDisplay= ? , preDeliveryDate= ? ,antenatalCareHospitalId = ? , " +
                "antenatalCareHospitalName = ? , babyBirthday = ? , babyGender = ? , isVIP = ? , " +
                "isCanTrialVIP = ? , vipEndTime = ? where tel = ? ";
        db.execSQL(
                sql,
                new Object[]{id, openId, identityId, name, pregnancyStatus, pregnancyStatusDisplay, preDeliveryDate,
                        antenatalCareHospitalId, antenatalCareHospitalName, babyBirthday, babyGender, isVIP, isCanTrialVIP, vipEndTime, tel});
    }

    /**
     * 用户姓名和身份证补充
     *
     * @param identityId 身份证号
     * @param name       姓名
     * @param tel        手机号
     */
    public void updateUserNameOrIdentity(String identityId, String name, String tel) {
        String sql = "update "
                + USER_TABLE
                + " set identityId= ? , name= ? where tel = ? ";
        db.execSQL(
                sql,
                new Object[]{identityId, name, tel});
    }

    /**
     * 用户医院补充
     *
     * @param antenatalCareHospitalName 医院名称
     * @param antenatalCareHospitalId   医院ID
     * @param tel                       用户手机号
     */
    public void updateUserHospital(String antenatalCareHospitalName, String antenatalCareHospitalId, String tel) {
        String sql = "update "
                + USER_TABLE
                + " set antenatalCareHospitalName= ? , antenatalCareHospitalId= ? where tel = ? ";
        db.execSQL(
                sql,
                new Object[]{antenatalCareHospitalName, antenatalCareHospitalId, tel});
    }

    /**
     * 用户会员信息更新
     *
     * @param isVIP         是否是VIP
     * @param isCanTrialVIP 是否可以试用VIP
     * @param vipEndTime    VIP结束时间
     * @param tel           用户手机号
     */
    public void updateUserVIP(int isVIP, int isCanTrialVIP, String vipEndTime, String tel) {
        String sql = "update "
                + USER_TABLE
                + " set isVIP= ? , isCanTrialVIP= ? , vipEndTime= ? where tel = ? ";
        db.execSQL(
                sql,
                new Object[]{isVIP, isCanTrialVIP, vipEndTime, tel});
    }

    /**
     * 查询方法
     *
     * @param data 用户表字段名
     * @return
     */
    public String select(String data) {
        String str = "";
        String sql = "select " + data + " from "
                + USER_TABLE;
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            // 根据列的索引直接读取 比如第0列的值
            str = c.getString(c.getColumnIndex(data));
        }
        return str;
    }

    // 查询方法
    public String select1() {
        String str = "";
        String sql = "select _id,tel,identityId,name,access_token,token_type,pregnancyStatus," +
                "pregnancyStatusDisplay,preDeliveryDate,antenatalCareHospitalId," +
                "antenatalCareHospitalName,babyBirthday,babyGender,isVIP,isCanTrialVIP,vipEndTime from "
                + USER_TABLE;
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            // 根据列的索引直接读取 比如第0列的值
            Log.e("用户数据信息start", "***********************************************************************************");
            Log.e("_id=", "=======" + c.getString(c.getColumnIndex("_id")));
            Log.e("tel=", "=======" + c.getString(c.getColumnIndex("tel")));
            Log.e("identityId=", "=======" + c.getString(c.getColumnIndex("identityId")));
            Log.e("name=", "=======" + c.getString(c.getColumnIndex("name")));
            Log.e("access_token=", "=======" + c.getString(c.getColumnIndex("access_token")));
            Log.e("token_type=", "=======" + c.getString(c.getColumnIndex("token_type")));
            Log.e("pregnancyStatus=", "=======" + c.getString(c.getColumnIndex("pregnancyStatus")));
            Log.e("pregnancyStatusDisplay=", "=======" + c.getString(c.getColumnIndex("pregnancyStatusDisplay")));
            Log.e("preDeliveryDate=", "=======" + c.getString(c.getColumnIndex("preDeliveryDate")));
            Log.e("antenatalCareHospitalId=", "=======" + c.getString(c.getColumnIndex("antenatalCareHospitalId")));
            Log.e("antenatalCareHospitalName=", c.getString(c.getColumnIndex("antenatalCareHospitalName")));
            Log.e("babyBirthday=", "=======" + c.getString(c.getColumnIndex("babyBirthday")));
            Log.e("babyGender=", "=======" + c.getString(c.getColumnIndex("babyGender")));
            Log.e("isVIP=", "=======" + c.getInt(c.getColumnIndex("isVIP")));
            Log.e("isCanTrialVIP=", "=======" + c.getInt(c.getColumnIndex("isCanTrialVIP")));
            Log.e("vipEndTime=", "=======" + c.getString(c.getColumnIndex("vipEndTime")));
            Log.e("用户数据信息end", "***********************************************************************************");
        }
        return str;
    }

    /**
     * 查询表是否为空
     *
     * @param data 表名
     * @return
     */
    public int selectNull(String data) {
        int number;
        Cursor c = db.rawQuery("select * from " + data, null);
        number = c.getCount();
        return number;
    }

    /**
     * 清空表
     *
     * @param data 需要删除的表名
     */
    public void delete(String data) {
        String sql = "delete from " + data;
        db.execSQL(sql);
        //初始化表ID
        db.execSQL("update sqlite_sequence set seq=0 where name='" + data + "'");
    }

    /**
     * 查询缓存数据
     *
     * @param data 字段名
     * @return
     */
    public String selectCache(String data) {
        String str = "";
        String sql = "select " + data + " from "
                + CACHE_TABLE;
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            // 根据列的索引直接读取 比如第0列的值
            str = c.getString(c.getColumnIndex(data));
        }
        return str;
    }

    /**
     * 缓存数据替换
     *
     * @param data 数据
     * @param name 字段名
     */
    public void updateCache(String data, String name) {
        String sql = "update "
                + CACHE_TABLE
                + " set " + name + "= ?";
        db.execSQL(
                sql,
                new Object[]{data});
    }

    /**
     * 添加缓存数据
     *
     * @param data 数据
     * @param name 字段名
     */
    public void insertCache(String data, String name) {
        String sql = "insert into " + CACHE_TABLE
                + "(" + name + ") values(?)";
        db.execSQL(
                sql,
                new Object[]{data});
    }

    /**
     * 体温监测基础设置
     *
     * @param FeverWarning  发烧预警温度
     * @param SleepWarning  蹬被子预警温度
     * @param ShowerWarning ShowerWarning
     */
    public void insertTemperatureSet(String FeverWarning, String SleepWarning, String ShowerWarning) {
        String sql = "insert into " + TEMPERATRUE_SET_TABLE
                + "(FeverWarning,SleepWarning,ShowerWarning) values(?,?,?)";
        db.execSQL(
                sql,
                new Object[]{FeverWarning, SleepWarning, ShowerWarning});
    }

    /**
     * 更新监测设置信息all
     *
     * @param FeverWarning  发烧预警温度
     * @param SleepWarning  蹬被子预警温度
     * @param ShowerWarning ShowerWarning
     */
    public void updateTemperatureSetAll(String FeverWarning, String SleepWarning, String ShowerWarning) {
        String sql = "update " + TEMPERATRUE_SET_TABLE
                + " set FeverWarning= ? , SleepWarning= ? , ShowerWarning= ? where _id = ? ";
        db.execSQL(
                sql,
                new Object[]{FeverWarning, SleepWarning, ShowerWarning, 1});
    }

    /**
     * 更新监测设置信息
     *
     * @param data 字段名
     * @param i    数据
     */
    public void updateTemperatureSetSingle(String data, int i) {
        String sql = "update " + TEMPERATRUE_SET_TABLE
                + " set " + data + "= ? where _id = ? ";
        db.execSQL(
                sql,
                new Object[]{i, 1});
    }

    //更新设备信息

    /**
     * 更新监测设置信息
     *
     * @param data 字段名
     * @param id   数据
     */
    public void updateTemperatureSetDevices(String data, String id) {
        String sql = "update " + TEMPERATRUE_SET_TABLE
                + " set " + data + "= ? where _id = ? ";
        db.execSQL(
                sql,
                new Object[]{id, 1});
    }

    /**
     * 查询体温设置
     *
     * @param data 字段名
     * @return
     */
    public String selectTemperature(String data) {
        String str = "";
        String sql = "select " + data + " from "
                + TEMPERATRUE_SET_TABLE;
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            // 根据列的索引直接读取 比如第0列的值
            str = c.getString(c.getColumnIndex(data));
        }
        return str;
    }

    /**
     * 体温监测历史数据
     *
     * @param Type           监测类型
     * @param State          监测状态
     * @param StartTime      监测开始时间
     * @param EndTime        监测结束时间
     * @param TotalTime      监测总时长
     * @param MonitoringData 温度数据
     * @param Note           备注
     * @param Method         处理措施
     * @param ImgRecord      图片记录
     * @param WarningRecord  预警记录
     */
    public void insertTemperatureData(int Type, int State, String StartTime,
                                      String EndTime, String TotalTime, String MonitoringData,
                                      String MonitoringDataTime, String WarningRecord, String Note,
                                      String Method, String ImgRecord) {
        String sql = "insert into " + TEMPERATRUE_DATA_TABLE
                + "(Type,State,StartTime,EndTime,TotalTime,MonitoringData,MonitoringDataTime,WarningRecord,Note," +
                "Method,ImgRecord) values(?,?,?,?,?,?,?,?,?,?,?)";
        try {
            db.execSQL(
                    sql,
                    new Object[]{Type, State, StartTime, EndTime, TotalTime, MonitoringData, MonitoringDataTime,
                            WarningRecord, Note, Method, ImgRecord});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param Type 用来检索的监测类别
     * @return 查询到的数据
     */
    public ArrayList<HashMap<String, String>> selectTemperatrueAll(int Type) {
        //创建保存数据的集合
        ArrayList<HashMap<String, String>> list = new ArrayList<>();
        HashMap<String, String> map = null;
        String StartTime = null;
        String EndTime = null;
        String data = null;
        String date = null;
        //查询数据
        String sql = "select _id,Type,State,StartTime,EndTime,TotalTime,MonitoringData,MonitoringDataTime," +
                "WarningRecord,Note,Method,ImgRecord from "
                + TEMPERATRUE_DATA_TABLE + " where Type=" + Type + " order by _id desc;";
        Cursor c = db.rawQuery(sql, null);
        //整理数据
        while (c.moveToNext()) {
            map = new HashMap<>();
            float f = 0.0f;
            float l = 0.0f;
            map.put("_id", c.getString(c.getColumnIndex("_id")));
            map.put("Type", c.getString(c.getColumnIndex("Type")));
            map.put("State", c.getString(c.getColumnIndex("State")));
            //处理开始和结束时间
            StartTime = c.getString(c.getColumnIndex("StartTime"));
            map.put("StartTime", StartTime);
            EndTime = c.getString(c.getColumnIndex("EndTime"));
            map.put("EndTime", EndTime);
            //处理列表显示的日期
            if (date == null) {
                date = EndTime;
                map.put("listShowTime", EndTime);
            } else {
                if (date.split(" ")[0].equals(EndTime.split(" ")[0])) {
                    map.put("listShowTime", null);
                } else {
                    map.put("listShowTime", EndTime);
                    date = EndTime;
                }
            }
            //处理体温数据
            data = c.getString(c.getColumnIndex("MonitoringData"));
            map.put("MonitoringData", data);
            map.put("TotalTime", c.getString(c.getColumnIndex("TotalTime")));
            map.put("MonitoringDataTime", c.getString(c.getColumnIndex("MonitoringDataTime")));
            map.put("WarningRecord", c.getString(c.getColumnIndex("WarningRecord")));
            map.put("Note", c.getString(c.getColumnIndex("Note")));
            map.put("Method", c.getString(c.getColumnIndex("Method")));
            map.put("ImgRecord", c.getString(c.getColumnIndex("ImgRecord")));
            //整理数据
            map.put("time", StartTime.substring(11, 16) + "~" + EndTime.substring(11, 16));
            String str[] = data.split(";");
            if (Type == 0) {
                for (int i = 0; i < str.length; i++) {
                    if (f < Float.parseFloat(str[i])) {
                        f = Float.parseFloat(str[i]);
                    }
                }
                data = f + "";
            } else if (Type == 1) {
                for (int i = 0; i < str.length; i++) {
                    if (f == 0.0f) {
                        f = Float.parseFloat(str[i]);
                    }
                    if (f > Float.parseFloat(str[i])) {
                        f = Float.parseFloat(str[i]);
                    }
                }
                data = f + "";
            } else if (Type == 2) {
                for (int i = 0; i < str.length; i++) {
                    if (f < Float.parseFloat(str[i])) {
                        f = Float.parseFloat(str[i]);
                    }

                    if (l == 0.0f) {
                        l = Float.parseFloat(str[i]);
                    }
                    if (l > Float.parseFloat(str[i])) {
                        l = Float.parseFloat(str[i]);
                    }

                }
                data = l + "~" + f;
            }
            map.put("data", data);
            list.add(map);
        }
        return list;
    }

    /**
     * 清空表
     *
     * @param _id 需要删除的数据id
     */
    public void deleteTemperatrueItem(String _id) {
        String sql = "delete from " + TEMPERATRUE_DATA_TABLE + " where _id=" + _id;
        db.execSQL(sql);
    }
}
